<?php
namespace Com\Pay;

//欧创微信公众号支付

class OuchuangGzhPay{

    private $config = array();


//    public function __construct($type,$config = null){
//
//        if($type == 'A20000000000101') {
//            $send_data = array(
//                'merchno' => 'A20000000000101',
//                'key' => '3CDC66A54DCDE3156AG8B850218B50G7',
//                'mch_id' => '100850000428112',
//            );
//        }elseif($type == 'A20000000000168') {
//            $send_data = array(
//                'merchno' => 'A20000000000168',
//                'key' => 'A266FDD10879444DD87GGG3E61A37F65',
//                'mch_id' => '100850000704373'
//            );
//        }elseif($type == 'A20000000000169'){
//            $send_data = array(
//                'merchno' => 'A20000000000169',
//                'key' => 'G89B05D0158B932A41777G2DD40E6722',
//                'mch_id' => '100850000756865'
//            );
//        }elseif($type == 'A20000000000199'){
//            $send_data = array(
//                'merchno' => 'A20000000000199',
//                'key' => '6D782FG8A05C05630A5BA3EEGF243CG5',
//                'mch_id' => '100850000944360'
//            );
//        }elseif($type == 'A20000000000200'){
//            $send_data = array(
//                'merchno' => 'A20000000000200',
//                'key' => 'GCE04DG4EB360DE1D9E338C21939ABGB',
//                'mch_id' => '100850000302067'
//            );
//        }
//        $this->config = $send_data;
//    }


    public function __construct($mchConfig,$config = null){
        $this->config = $mchConfig;
    }

    /*生成支付按钮*/
    public function getCode($order_info)
    {

    }


    /*生成支付连接*/
    public function getUrl($order_info){
        $price = $order_info['paymoney'];
        $returnUrl = $order_info['return_url'];
        $notifyUrl = 'http://' . $_SERVER['HTTP_HOST'].'/Api/NotifyCallback/OuchuangGzhPay';

        // var_dump($notifyUrl);die;
        $order_sn = $order_info['ordernumber'];
        $post_data = array(
           "merchno" => $this->config['appid'],
            "org_id" => "10000095",
            "out_trade_no" => $order_sn,
            'ordDt' => date('Ymd'),
            "total_fee" => $price * 100, // 单位：分
            "body" => "OuchuangGzhPay",
          "notify_url" => $notifyUrl,
          "serverUrl" => $returnUrl,
          "nonce_str" => $this->getNonceStr(13) // 随机生成不重复的字符串
       );

        $post_data['sign'] = $this->setSign($post_data,$this->config['mch_key'],false);
        $tar_url = 'http://ouchuang.xjoyt.com:8099/OuYaZhiFu/oytWXcommon.action?' . http_build_query($post_data);
        return $tar_url;
    }

   // 生成签名方法
    private function setSign($data,$skey,$Is_Notify){
        if($Is_Notify){
            $strMd5 = strtoupper(md5("org_id=" . $data['org_id'] . '&merchno=' . $data['merchno'] . '&out_trade_no=' . $data['out_trade_no'] .  '&trade_type=' . $data['trade_type'] .'&trade_state=' . $data['trade_state']. '&total_amt=' . $data['total_amt'] . '&key=' . $skey));
            return $strMd5;
        }
        $Mysign = strtoupper(md5('merchno=' . $data['merchno'] . '&org_id=' . $data['org_id'] . '&ordDt=' . $data['ordDt']  . '&total_fee=' . $data['total_fee'] . '&body=' . $data['body'] . '&notify_url=' . $data['notify_url'] . '&serverUrl='. $data['serverUrl'] . '&nonce_str=' . $data['nonce_str'].'&key=' . $this->config['mch_key']));
        return $Mysign;
}


    //回调方法，把返回数据处理成统一规定返回
    public function response($data){
        $Mysign = $this->setSign($data,$this->config['mch_key'],true);
        if($Mysign === $data['sign']){
            if($data['trade_state'] == 'SUCCESS'){
                return true;
            }else{
                // 失败
                return false;
            }
        }else{
            // 失败
            return false;
        }
    }

    function getNonceStr($length = 32)
    {
        $chars = "0123456789abcdef";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return str_shuffle($str);
    }


    public function curl_json_post($url,$data)
    {
        if(is_array($data)){
            $data_string = json_encode($data);
        }else{
            $data_string = $data;
        }
        $ch = curl_init($url);
        // curl_setopt($ch, CURLOPT_TIMEOUT,5);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string))
        );
        $result = curl_exec($ch);
        curl_close ( $ch );
        return $result;
    }

    public function curl_post($url, $data){
        $data = http_build_query($data);
        // file_put_contents('./tmp.txt',$data);
        //echo '<br>'.$data.'<br>';
        // mb_strlen($str,'utf-8');
        // var_dump((mb_strlen($data,'utf-8') == strlen($data)));
        $opts = array(
            'http'=>array(
                'method'=>"POST",
                'timeout'=>60,
                'header'=>"Content-type: application/x-www-form-urlencoded\r\n".
                    "Content-length:".mb_strlen($data,'utf-8')."\r\n" .
                    "Cookie: foo=bar\r\n" .
                    "\r\n",
                'content' => $data,
            )
        );
        $cxContext = stream_context_create($opts);
        $result = file_get_contents($url, false, $cxContext);
        return $result;
    }

    private function gbkToUtf8($arr){
        if(is_array($arr)){
            $res = array();
            foreach($arr as $k => $v){
                $res[$k] = $this->gbkToUtf8($v);
            }
            return $res;
        }else{
            return mb_convert_encoding ( $arr, "UTF-8", "GBK" );
        }
    }


}
